package com.atguigu.tingshu.live.config;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.model.live.FromUser;
import com.atguigu.tingshu.model.live.SocketMsg;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.annotation.PostConstruct;
import jakarta.websocket.Session;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/*
    直播间 聊天室容器
        用来存储直播间所有的用户信息
        并通知直播间用户最新的消息
 */
//@Component
public class WebSocketLocalContainer {//聊天室用户数据缓存管理
    //用户id列表Map: roomId-> userIds
    private static Map<Long , Set<Long>> userIdsMap = new ConcurrentHashMap<>();
    // 用户列表：  用户Id-> 用户对象
    private static Map<Long , FromUser> userMap = new ConcurrentHashMap<>();
    // 用户的会话列表：  userId-> Session
    private static Map<Long , Session> sessionMap = new ConcurrentHashMap<>();
//    @Autowired
//    RedissonClient  redissonClient;
//
//    static RedissonClient client;
//    @PostConstruct
//    public void init(){
////        userIdsMap = redissonClient.getMap("ts:live:userIds");
////        userMap = redissonClient.getMap("ts:live:user");
////        sessionMap = redissonClient.getMap("ts:live:session");
//        client = redissonClient;
//    }


    //1、客户端和ws建立连接时，需要将 用户Id  用户   会话对象存到map中
    public static void addUser2LiveRoom(Session session , Long roomId ,  UserInfo userInfo){
        //获取用户信息
        Long userInfoId = userInfo.getId();
//        userIdsMap = client.getMap("ts:live:userIds");
        //添加用户到直播间用户列表中
        Set<Long> userIds = userIdsMap.get(roomId);
        if(userIds==null){
            userIds = new HashSet<>();
            userIdsMap.put(roomId , userIds);
        }
        userIds.add(userInfoId);
        //保存用户信息
//        userMap = client.getMap("ts:live:user");
        FromUser fromUser = new FromUser();
        fromUser.setUserId(userInfoId);
        fromUser.setAvatarUrl(userInfo.getAvatarUrl());
        fromUser.setNickname(userInfo.getNickname());
        userMap.put(userInfoId , fromUser);
        //保持会话
//        sessionMap = client.getMap("ts:live:session");
        sessionMap.put(userInfoId , session);
    }
    //2、ws客户端断开时，将用户移除直播间
    public static void removeUserFromLiveRoom(Long roomId , UserInfo userInfo){
        Long userId = userInfo.getId();
//        userIdsMap = client.getMap("ts:live:userIds");
//        userMap = client.getMap("ts:live:user");
//        sessionMap = client.getMap("ts:live:session");
        Set<Long> userIds = userIdsMap.get(roomId);
        if(!CollectionUtils.isEmpty(userIds)){
            userIds.remove(userId);
        }
        userMap.remove(userId);
        sessionMap.remove(userId);

    }

    //3、将最新消息发送给直播间所有用户
    public static void sendMsg(Long roomId , SocketMsg socketMsg){
        if(socketMsg.getMsgType().equals(SocketMsg.MsgTypeEnum.HEART_BEAT.getCode()) ||
                socketMsg.getMsgType().equals(SocketMsg.MsgTypeEnum.TOKEN_INVALID.getCode())){
            //心跳消息 和token无效消息 直接结束
            return;
        }
        //获取直播间所有用户id
//        userIdsMap = client.getMap("ts:live:userIds");
//        sessionMap = client.getMap("ts:live:session");
        Set<Long> userIds = userIdsMap.get(roomId);
        if(!CollectionUtils.isEmpty(userIds)){
            userIds.forEach(userId->{
                //发送消息
                //1、获取用户的会话
                Session session = sessionMap.get(userId);

                //2、发送消息
                session.getAsyncRemote()//异步发送消息
                        .sendText(JSONObject.toJSONString(socketMsg));
            });
        }

    }
}
